"""
  Copyright (c) 2024 Northeastern University (China)
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""
import json
import bson
import io
from . import mongodb
from src.common_utils.utils_file import decompress_dict


class Component(mongodb.MongoDB):
    db_name = "HarmonyOSS"
    collection_name = "Component"
    def  __init__(self):
        super().__init__("HarmonyOSS", "Component")

    def get_data(self,filter,field,count=0):
        return self.get(filter,field,count)

    def get_data_count(self):
        return self.get_document_count()

    def get_many_data(self, filter, field):
        large_data = self.get_large_data(filter, field)
        for data in large_data:
            yield data
    def add_meta(self, dic):
        self.add_one(dic)
    def update_one(self,_id,content):
        #利用id修改值
        return self.update_one_with_id(_id,content)
    def add_meta_update_repeat(self,condition,dic):
        print(f"已经有的组件重新分割一下{condition}")
        self.update_one_with_condition(condition, dic)
    def Gridfs_store(self,file,filename):
        return self.use_Gridfs_store(file,filename)
    def Gridfs_get(self,file_id):
        return self.use_Gridfs_get(file_id)
    def Gridfs_remove(self,file_id):
        return self.use_Gridfs_delete(file_id)

    # def get_all_features(self,filter,field):
    #     all=self.get(filter,field)
    #     for doc in all:
    #         sig_info = doc['func_feature']
    #         if isinstance(sig_info, dict):
    #             pass
    #         elif isinstance(sig_info, bson.objectid.ObjectId):
    #             real_info=self.Gridfs_get(sig_info)
    #             if real_info is not None:
    #                  # 将字节流数据转换为字符串
    #                 json_str = real_info.decode('utf-8')
    #                 # 将字符串反序列化为字典
    #                 data_dict = json.loads(json_str)
    #                 doc['func_feature']=data_dict
    #         else:
    #             print(f"func_feature类型错误")
    #         yield doc
    def get_all_features(self,filter,field,count:int=0):
        all=self.get_large_data(filter,field,count,db_name=self.db_name,collection_name=self.collection_name)
        for doc in all:
            sig_info = doc['func_feature']
            if isinstance(sig_info, bytes):
                data=decompress_dict(sig_info)
                doc['func_feature'] = data
            elif isinstance(sig_info, bson.objectid.ObjectId):
                real_info=self.Gridfs_get(sig_info)
                if real_info is not None:
                     data=decompress_dict(real_info)
                     doc['func_feature']=data
            else:
                print(f"func_feature类型错误")

            yield doc

    def get_one_feature(self, filter, field, count: int = 0):
        all = self.get(filter, field, count)
        for doc in all:
            sig_info = doc['func_feature']
            if isinstance(sig_info, bytes):
                data = decompress_dict(sig_info)
                doc['func_feature'] = data
            elif isinstance(sig_info, bson.objectid.ObjectId):
                real_info = self.Gridfs_get(sig_info)
                if real_info is not None:
                    data = decompress_dict(real_info)
                    doc['func_feature'] = data
            else:
                print(f"func_feature类型错误")

        return all
    def update_func_feature_by_id(self,id,sig_info,sig_full_name):
        # 定义字段大小的阈值
        threshold = 15800000  # 默认为 mongodb支持的最大字节
        # 将数据序列化为 BSON
        bson_data = bson.BSON.encode(sig_info)
        # 获取序列化后的数据大小
        bson_size = len(bson_data)
        print(f"func_dict的大小{bson_size}")
        if bson_size <= threshold:
            print(f"使用普通存储方式")
            self.update_one_with_id(id, {'func_feature': sig_info})
        else:
            print(f"使用gridfs存储方式")
            json_data = json.dumps(sig_info)
            sig_info_id = self.use_Gridfs_store(io.BytesIO(json_data.encode()), sig_full_name + ".json")
            old_fileid=self.get_data({'_id':id},{'func_feature':1,'_id':0})[0]
            self.Gridfs_remove(old_fileid)
            self.update_one_with_id(id,{'func_feature':sig_info_id})

    def load_dict_keys_from_db(self,filter):
        res=[]
        cursor = self.get(filter, {"func_feature": 1})  # 查询数据库，只加载 "func_feature" 字段
        for doc in cursor:
            if "func_feature" in doc:
                sig_info = doc["func_feature"]
                if isinstance(sig_info, bytes):
                    data = decompress_dict(sig_info)
                    sig_info = data
                elif isinstance(sig_info, bson.objectid.ObjectId):
                    real_info = self.Gridfs_get(sig_info)
                    if real_info is not None:
                        data = decompress_dict(real_info)
                        sig_info= data
                else:
                    print(f"func_feature类型错误")
                for key in sig_info.keys():
                    res.append(key)
        return res
